package com.dailyblue.java.thread;

import lombok.SneakyThrows;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// 线程池
public class DemoI {

    static class I implements Runnable {
        @SneakyThrows
        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始执行了");
            Thread.sleep(1000);
        }
    }

    static class I2 implements Runnable {
        @SneakyThrows
        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始执行了");
        }
    }

    @SneakyThrows
    private static void a() {
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            I i1 = new I();
            // 将任务交由线程池执行
            service.execute(i1);
            Thread.sleep(100);
        }
        service.shutdown();
    }

    @SneakyThrows
    private static void b() {
        ExecutorService service = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            I i1 = new I();
            // 将任务交由线程池执行
            service.execute(i1);
        }
        service.shutdown();
    }

    @SneakyThrows
    private static void c() {
        ExecutorService service = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 10; i++) {
            I i1 = new I();
            // 将任务交由线程池执行
            service.execute(i1);
        }
        service.shutdown();
    }

    @SneakyThrows
    private static void d() {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(4);
        I2 i = new I2();
        //service.schedule(i, 3, TimeUnit.SECONDS);
        service.scheduleWithFixedDelay(i,3,2,TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        d();
    }
}
